package com.dat255.tentatime.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class TTDbAdapter {

	// Database fields
	public static final String KEY_ROWID = "_id";
	public static final String KEY_ID = "examId";
	public static final String KEY_NAME = "examName";
	public static final String KEY_TIME = "examTime";
	public static final String KEY_DATE = "examDate";
	public static final String KEY_PLACE = "examPlace";
	private static final String DATABASE_TABLE = "exam";
	private Context context;
	private SQLiteDatabase database;
	private TTimeDbHelper dbHelper;

	public TTDbAdapter(Context context) {
		this.context = context;
	}

	public TTDbAdapter open() throws SQLException {
		dbHelper = new TTimeDbHelper(context);
		database = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		dbHelper.close();
	}

	
/**
	 * Create a new exam If the exam is successfully created return the new
	 * rowId for that note, otherwise return a -1 to indicate failure.
	 */

	public long createExam(String id, String name, String time,
			String date, String place) {
		ContentValues initialValues = createContentValues(id, name,
				time ,date ,place );

		return database.insert(DATABASE_TABLE, null, initialValues);
	}

	
/**
	 * Update the exam
	 */

	public boolean updateExam(long rowId, String id, String name,
			String time, String date, String place) {
		ContentValues updateValues = createContentValues(id, name,
				time, date, place);

		return database.update(DATABASE_TABLE, updateValues, KEY_ROWID + "="
				+ rowId, null) > 0;
	}

	
/**
	 * Deletes exam
	 */

	public boolean deleteExam(long rowId) {
		return database.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	
/**
	 * Return a Cursor over the list of all exam in the database
	 * 
	 * @return Cursor over all exams
	 */

	public Cursor fetchAllExams() {
		return database.query(DATABASE_TABLE, new String[] { KEY_ROWID,
				KEY_ID, KEY_NAME, KEY_TIME, KEY_DATE, KEY_PLACE }, null, null, null,
				null, null);
	}

	
/**
	 * Return a Cursor positioned at the defined exam
	 */

	public Cursor fetchExam(long rowId) throws SQLException {
		Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] {
				KEY_ROWID, KEY_ID, KEY_NAME, KEY_TIME, KEY_DATE, KEY_PLACE },
				KEY_ROWID + "=" + rowId, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	private ContentValues createContentValues(String id, String name,
			String time, String date, String place) {
		ContentValues values = new ContentValues();
		values.put(KEY_ID, id);
		values.put(KEY_NAME, name);
		values.put(KEY_TIME, time);
		values.put(KEY_DATE, date);
		values.put(KEY_PLACE, place);
		return values;
	}
}